<template>
  <div>
    <div class="class-layout">
      <!-- 头部区域 -->
      <header v-if="showHeader" class="header">
        <div class="overlay"></div>
        <div class="header-content">
          <div class="class-info">
            <div>
              <button @click="goBack">← 返回试卷库</button> <!-- 返回按钮 -->
              <h1>创建试卷</h1>
              <p>请填写以下信息以创建新的试卷</p>
            </div>
          </div>
        </div>
      </header>

      <!-- 侧边栏和主内容区 -->
      <div class="main-container">
        <div class="container">
          <!-- 表单标题 -->
          <div class="form-header">
            <h2>试卷基础信息</h2>
          </div>
          <!-- 表单开始 -->
          <form @submit.prevent="submitExam">
            <!-- 试卷名称输入框 -->
            <div class="form-group">
              <label for="examName">试卷名称</label>
              <input type="text" id="examName" v-model="examName" placeholder="请输入试卷名称" required />
            </div>

            <!-- 方向和课程选择框 -->
            <div class="form-group">
              <label for="courseDirection">方向&课程</label>
              <select id="courseDirection" v-model="courseDirection" required>
                <option value="">请选择方向&课程</option>
                <option v-for="direction in directions" :key="direction.direction_id" :value="direction.direction_id">
                  {{ direction.direction_title }}
                </option>
              </select>
              <a href="#" class="help-link">没有合适的方向&课程？联系教研助理</a>
            </div>

            <!-- 难度选择 -->
            <div class="form-group">
              <label>难度</label>
              <div class="difficulty-options">
                <label><input type="radio" value="0" v-model="difficulty" /> 简单</label>
                <label><input type="radio" value="1" v-model="difficulty" /> 适中</label>
                <label><input type="radio" value="2" v-model="difficulty" /> 困难</label>
              </div>
            </div>

            <!-- 答题时长输入框 -->
            <div class="form-group">
              <label for="timeLimit">答题时长</label>
              <input type="number" id="timeLimit" v-model="timeLimit" placeholder="请输入答题时长（分钟）" required min="1" />
            </div>

            <!-- 试卷须知文本框 -->
            <div class="form-group">
              <label for="examInstructions">试卷须知</label>
              <textarea id="examInstructions" v-model="examInstructions" placeholder="请输入试卷须知"></textarea>
            </div>

            <!-- 按钮区 -->
            <div class="form-buttons">
              <button type="button" @click="goBack" class="cancel-button">取消</button>
              <button type="submit" class="next-button">下一步</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { watch } from 'vue';
import { ElMessage } from 'element-plus';
import {  getQuestionDirections, createPaper,createExamWithClass } from '@/services/api'; // 导入API

export default {
  setup() {
    const router = useRouter();
    const route = useRoute();
    const currentTab = ref('all');
    const directions = ref([]);
    const examName = ref(''); // 试卷名称
    const courseDirection = ref(''); // 方向ID
    const difficulty = ref(1); // 难度默认值 (适中)
    const timeLimit = ref(60); // 答题时长
    const examInstructions = ref(''); // 试卷须知
    const semesterId = ref(route.params.semesterId);

watch(() => route.params.semesterId, (newId) => {
  semesterId.value = newId;
  console.log('学期 ID 变更:', newId);
});

    const goBack = () => {
      router.push('/teacher/T_exam_bank'); // 返回到试卷库
    };

    const showHeader = computed(() => route.path.includes('/class-management'));

    const fetchDirections = async () => {
      try {
        const response = await  getQuestionDirections();
        if (response.data.status === 1 && response.data.code === 'S0000') {
          directions.value = response.data.data;
        }
      } catch (error) {
        console.error('获取方向列表失败:', error);
      }
    };
    const techId = ref(localStorage.getItem('id')); // Vue 响应式引用
const submitExam = async () => {
  if (!techId.value) {
    ElMessage.error('用户未登录或登录信息丢失，请重新登录！');
    return;
  }
  const paperData = {
    tech_id: parseInt(techId.value),
    paper_title: examName.value,
    paper_content: examInstructions.value,
    difficulty: parseInt(difficulty.value),
    direction_id: parseInt(courseDirection.value),
    during_time: parseInt(timeLimit.value, 10), 
  };
  try {
    let response;
    
    if (semesterId.value) {
      // 课堂创建逻辑
      response = await createExamWithClass({
        sem_id: parseInt(semesterId.value),
        paperHeader: paperData
      });
      if (response.data.status === 1) {
        ElMessage.success('试卷创建成功！');
        // 添加来源标识参数
       router.push({
          path: `/edit-exam/${response.data.data.paper_id}`,
          query: {
            source: 'class',
            examId: response.data.data.exam_id, // 传递 exam_id
            semesterId: response.data.data.sem_id,   // 传递 sem_id
          }
        });
      }
    } else {
      // 试卷库创建逻辑
      response = await createPaper(paperData);
      if (response.data.status === 1) {
        ElMessage.success('试卷创建成功！');
        // 添加来源标识参数
        router.push(`/edit-exam/${response.data.data.paper_id}?source=bank`);
      }
    }
  } catch (error) {
    console.error('网络错误:', error);
    ElMessage.error('试卷创建失败，请检查网络连接或稍后重试！');
  }
};
    onMounted(() => {
      fetchDirections();
    });

    return {
      examName,
      directions,
      courseDirection,
      difficulty,
      timeLimit,
      examInstructions,
      goBack,
      showHeader,
      submitExam,
       currentTab, 
       semesterId,
    };
  },
};
</script>


<style scoped>
/* 布局样式 */
.class-layout {
  display: flex;
  flex-direction: column;
  width: 100%;
  margin: 0 auto;
  background: white;
}

.main-container {
  display: flex;
  flex-grow: 1;
  width: 100%;
}

.content {
  flex-grow: 1;
  padding: 40px;
  background-color: white;
  overflow-y: auto;
  margin-left: 20px;
  border-radius: 10px;
  width: 60%;
  margin-top: 3px;
}

/* 头部样式 */
.header {
  background-color: #244382;
  padding: 30px 40px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin: 20px 0;
  border-radius: 10px;
  color: white;
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 1;
  border-radius: 10px;
}

.header-content {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 表单容器样式 */
.container {
  width: 100%;
  margin: 0 auto;
  background-color: #ffffff;
  padding: 20px 40px;
}

.form-header {
  text-align: center;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
}

input[type="text"],
input[type="number"],
select,
textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
}

.difficulty-options label {
  margin-right: 15px;
  font-weight: normal;
}

textarea {
  height: 80px;
}

.help-link {
  font-size: 12px;
  color: #244382;
  text-decoration: none;
}

.help-link:hover {
  text-decoration: underline;
}

.form-buttons {
  display: flex;
  justify-content: space-between;
}

.cancel-button,
.next-button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.cancel-button {
  background-color: #999;
  color: white;
}

.next-button {
  background-color: #125aa2;
  color: white;
}

.next-button:hover {
  background-color: #0e4b8a;
}
</style>
